<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\controller\Common;
use think\Request;
use app\admin\model\Admin as MainModel;
use app\admin\model\AuthGroup as AuthGroupModel;
use think\facade\View;

class Admin extends Common
{
	public function __construct(){
		parent::__construct();

		$this->model = new MainModel;
		View::assign('model',$this->model);
		View::assign('title',"管理员");
		$this->validate = new \app\admin\validate\Admin;

		$grouplist = AuthGroupModel::column("title","id");
		View::assign('grouplist',$grouplist);

		/**
		 * 表结构
		 */
		$this->tables = config('tables.admin');
		View::assign('tables',$this->tables);
	}
	
	/**
	 * 搜索条件
	 */
	protected function search(){
		$admin = session('administrator');
		$id = intval($admin['id']);
		$where[] = ['is_admin','=',0];
		$where[] = ['id','<>',$id];
		return $where;
	}

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(Request $request)
    {
		if('POST' == $request->method()){
			$id = intval(input('post.id'));
			$validate = new \app\admin\validate\Admin;
			$validate->rule = [
				'username'=>'require|unique:admin,username,'.$id.',id|length:1,50',
			];
			$validate->message = [
				'username.require' => '用户名不能为空！',
				'username.unique' => '用户名已经存在！',
				'username.length' => '用户名长度错误！',
			];
				
			$re = $this->update($request,$validate);

			if(!empty($re)){
				return $re;
			}
		}

		$id = intval(input('param.id'));
		$info = $this->model->find($id);
		return view('edit',[
			'info'=>$info
		]);	
    }

	
	/**
	 * 修改个人信息
	 */
	public function profile(Request $request){
		$admin = session('administrator');

		$id = intval($admin['id']);
		$validate = new \app\admin\validate\Profile;
		$validate->rule['username'] = 'require|unique:admin,username,'.$id.',id|length:1,50';

		$re = $this->update($request,$validate,'profile');
		if(!empty($re)){
			return $re;
		}

		View::assign('title',"个人信息");
		return view('profile',[
			'info'=>$admin
		]);
	}

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(Request $request)
    {
		$id = $request->param('id');
		if(!empty($id)){
			$idarr = explode(',',$id);
			foreach($idarr as $key=>$value){
				$admin = $this->model->find($value);
				$idlist = $admin->groups()->column('id');
				$admin->groups()->detach($idlist);
			}
			$msg = $this->model->destroy($idarr);
			if($msg){
				return json([
					'status'=>1,
					'notice'=>"删除成功！",
				]);
			} else {
				return json([
					'status'=>2,
					'notice'=>"删除失败！",
				]);
			}
		} else {
			return json([
				'status'=>2,
				'notice'=>"ID 不能为空！",
			]);
		}
    }

}
